package sdk.pay.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import sdk.pay.constant.PayConfigure;
import sdk.pay.constant.PayConstant;
import sdk.pay.model.TimeStatisticsModel;
import sdk.pay.sqlite.DatabaseControl;
import sdk.pay.sqlite.DatabaseHelper;

/**
 * Created by Joe on 2017/6/10 0010 14:43.
 * TimeStatisticsUtils
 */

public class PayTimeStatisticsUtil {
    private static TimeStatisticsModel sTimeStatisticsModel;
    private static SQLiteDatabase db;
    private int historyNumber = 5;
    private static SharedPreferences mSharedPreferences;

    /*do nothing only  instantiation*/
    PayTimeStatisticsUtil() {
        if (mSharedPreferences != null) {
            historyNumber = mSharedPreferences.getInt(PayConstant.SHAREPERFERENCE_TIMR_HISTORY, 5);
        }
    }

    public PayTimeStatisticsUtil(Context context) {
        sTimeStatisticsModel = new TimeStatisticsModel();
        DatabaseHelper helper = new DatabaseHelper(context, PayConstant.DATABASE_NAME, null);
        db = helper.getWritableDatabase();
        mSharedPreferences = context.getSharedPreferences(PayConstant.SHAREPERFERENCE_NAME, Context.MODE_PRIVATE);
        historyNumber = mSharedPreferences.getInt(PayConstant.SHAREPERFERENCE_TIMR_HISTORY, 5);

    }

    /*when error upload*/
    public void doErrorUpload() {
        PayLogUtil.logFifth("PayTimeStatisticsUtil doErrorUpload");
        sTimeStatisticsModel.setRemark("Error");
        insertData();
        ArrayList<TimeStatisticsModel> arrayList = DatabaseControl.getAllDatas(db);
        if (arrayList == null) {
            PayLogUtil.logFourth("PayTimeStatisticsUtil dataUpload arrayList null");
            return;
        }
        dataUpload(arrayList);
    }

    /*when  the number of local saved  records more than the historyNumber value,upload*/
    public void doUploadIfNeeded() {
        PayLogUtil.logFifth("PayTimeStatisticsUtil doUploadIfNeeded");
        ArrayList<TimeStatisticsModel> arrayList = DatabaseControl.getAllDatas(db);
        if (arrayList == null) {
            PayLogUtil.logFourth("PayTimeStatisticsUtil dataUpload arrayList null");
            return;
        }
        if (arrayList.size() >= historyNumber) {
            dataUpload(arrayList);
        }
    }

    /*do insert one model*/
    public void insertData() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sTimeStatisticsModel.setSystemTime(dateFormat.format(new Date()));
        DatabaseControl.insertData(db, sTimeStatisticsModel);
    }

    /*do update callback data*/
    public void updateData() {
        DatabaseControl.updateData(db, sTimeStatisticsModel);
    }

    /*getTimeStatisticsModel*/
    public TimeStatisticsModel getTimeStatisticsModel() {
        return sTimeStatisticsModel == null ? new TimeStatisticsModel() : sTimeStatisticsModel;
    }

    /*Destruction of TimeStatisticsUtils' resources*/
    public void destroyTimeStatisticsUtils() {
        sTimeStatisticsModel = null;
        if (db != null) {
            db.close();
        }
    }

    private void dataUpload(ArrayList<TimeStatisticsModel> arrayList) {
        JSONObject jsonObject = new JSONObject();
        try {
            JSONArray jsonArray = new JSONArray();
            for (TimeStatisticsModel model : arrayList) {

                JSONObject jsonObject_Item = new JSONObject();
                jsonObject_Item.put("platform", model.getPlatform());//
                jsonObject_Item.put("area", model.getArea());//
                jsonObject_Item.put("deviceType", model.getDeviceType());//
                jsonObject_Item.put("netType", model.getOperator());//
                jsonObject_Item.put("serviceTime", model.getServiceTime());//
                jsonObject_Item.put("serviceInfo", model.getServiceInfo());//
                jsonObject_Item.put("tokenTime", model.getTokenTime());//
                jsonObject_Item.put("tokenInfo", model.getTokenInfo());//
                jsonObject_Item.put("paylistTime", model.getPaylistTime());//
                jsonObject_Item.put("paylistInfo", model.getPaylistInfo());//
                jsonObject_Item.put("payUrlTime", model.getPayUrlTime());//
                jsonObject_Item.put("payUrlInfo", model.getPayUrlInfo());//
                jsonObject_Item.put("payTime", model.getPayTime());//
                jsonObject_Item.put("payInfo", model.getPayInfo());//
                jsonObject_Item.put("callbackTime", model.getCallbackTime());//
                jsonObject_Item.put("callbackInfo", model.getCallbackInfo());//
                jsonObject_Item.put("systemTime", model.getSystemTime());//
                jsonObject_Item.put("remark", model.getRemark());//
                jsonObject_Item.put("orderNumber", model.getOrderNumber());//
                jsonObject_Item.put("getTokenUrl", model.getTokenUrl());//
                jsonObject_Item.put("usercode", model.getUserCode());//
                jsonArray.put(jsonObject_Item);

            }
            jsonObject.put("info", jsonArray);//

            DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String key = PayMD5Util.getMD5(dateFormat.format(new Date()));
            String encode = PayDESUtil.encode("wolegequ" + key, jsonObject.toString());
            RequestBody requestBody = new FormBody.Builder()
                    .add("nonce", key)
                    .add("info", encode)
                    .build();
            doUploadDatas(requestBody);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void doUploadDatas(RequestBody requestBody) {
        String url = PayConfigure.UPLOAD_LOG_API;
        PayLogUtil.logFifth("PayTimeStatisticsUtil doUploadDatas");
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder().connectTimeout(PayConstant.TIME_OUT,
                TimeUnit.SECONDS).readTimeout(PayConstant.TIME_OUT, TimeUnit.SECONDS).build();
        mOkHttpClient.newCall(new Request.Builder().url(url).post(requestBody).build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                PayLogUtil.logFourth("PayTimeStatisticsUtil doUploadDatas onFailure IOException = " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (null != response.body()) {
                    String result = response.body().string();
                    PayLogUtil.logFourth("PayTimeStatisticsUtil doUploadDatas onResponse result = " + result);
                    if (response.isSuccessful()) {
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            String flag = jsonObject.getString("flag");
                            if (flag.equals("1")) {
                                String decode = PayDESUtil.decode("wolegequ" + jsonObject.getString("nonce"),
                                        jsonObject.getString("msg"));
                                historyNumber = Integer.parseInt(new JSONObject(decode).getString("uploadfew"));
                                SharedPreferences.Editor editor = mSharedPreferences.edit();
                                editor.putInt(PayConstant.SHAREPERFERENCE_TIMR_HISTORY, historyNumber);
                                editor.apply();
                                DatabaseControl.deleteTable(db);
                            } else {
                                PayLogUtil.logFourth("PayTimeStatisticsUtil doUploadDatas result error");
                            }

                        } catch (JSONException | NumberFormatException e) {
                            e.printStackTrace();
                            PayLogUtil.logFourth("PayTimeStatisticsUtil doUploadDatas onResponse jsonObject error");
                        }

                    } else {
                        PayLogUtil.logFourth("PayTimeStatisticsUtil doUploadDatas onResponse failure");
                    }
                } else {
                    PayLogUtil.logFourth("PayTimeStatisticsUtil doUploadDatas response body = null");
                }
            }
        });
    }
}

